package com.hotau.location;

import java.util.Timer;
import java.util.TimerTask;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.framework.HeaderNotVisible;
import com.hotau.util.PreferencesUtils;

public class LoadingFragment extends Fragment implements HeaderNotVisible{
	
	private TextView loading_show_version;

	private Timer mAniTimer;
	private AnimationTimer mAniTimerTask;
	private AnimationDrawable mAnim;
	private static final int duration=3*1000;
	 private Handler mHandler=new Handler(){
		 @Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				HotauActivity nextActivity = (HotauActivity) getActivity();
				if (nextActivity != null) {
					String instruction=PreferencesUtils.getInstruction(nextActivity);
					if(PreferencesUtils.VALUE_INSTRUCTION_READ.equals(instruction)){
						nextActivity.pushFragment("", new TogetherFragment());
					}else{
						nextActivity.pushFragment("", new InstructionFragment());
					}
				}
				
			}
	 };
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
		
		loading_show_version = (TextView) getActivity().findViewById(
				R.id.loading_show_version);
		// 给版本号赋值
		loading_show_version.setText(HotauConstants.getAppVersion(getActivity()));
		
		ImageView iv = (ImageView) getActivity().findViewById(
				R.id.logining_anim_imgview);
		mAnim = (AnimationDrawable) iv.getBackground();
		mAniTimerTask = new AnimationTimer(mAnim);

		startAnimation();
		
		mAniTimer.schedule(new TimerTask(){

			@Override
			public void run() {
				stopAnimation();		
			//跳转登录页面
				mHandler.sendEmptyMessage(0);
			}
			
		}, duration);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		return inflater.inflate(R.layout.location_loading, container, false);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
	}

	public void startAnimation() {
		if (mAniTimer == null) {
			mAniTimer = new Timer(true);
			mAniTimer.schedule(mAniTimerTask, 100);
		}
	}

	public void stopAnimation() {
		if (mAniTimer != null) {
			mAnim.stop();
			mAniTimerTask.cancel();
			mAniTimer.cancel();
			mAniTimer = null;
		}
	}

	private static class AnimationTimer extends TimerTask {
		AnimationDrawable animation;

		public AnimationTimer(AnimationDrawable animation) {
			this.animation = animation;
		}

		@Override
		public void run() {
			animation.start();
			this.cancel();
		}

	}
}
